import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_ys7/flutter_ys7.dart';
import 'package:permission_handler/permission_handler.dart';

import '../../components/status/toast.dart';

class Video {
  // 视频流所需参数
  static String _sdk;
  static String _token;
  static String _serialNum;
  static String _code;

  // 统计开启视频次数
  static int _num = 0;

  // 存储定时器
  static Timer _canclTimer = null;

  // 是否有视频被开启
  static bool _existVideo = false;

  /// 开启视频播放
  /// * [callback] Function|回调函数|必填
  startRealPlay({@required Function callback}) async {
    // 销毁后播放
    if (_existVideo) await releaseRealPlay();

    _canclTimer = Timer(Duration(seconds: 2), () async {
      try {
        // 初始化SDK
        await FlutterYs7.initSdk(_sdk);

        // 设置AccessToken
        await FlutterYs7.setAccessToken(_token);

        // 初始化视频播放器
        await FlutterYs7.initEZPlayer(_serialNum, _code, 1);

        // 开始实时播放
        bool state = await FlutterYs7.startRealPlay();

        // 记录是否开启视频流
        _existVideo = state;

        // 执行回调
        if (callback != null)
          callback({"isComplete": state, "isConnectFail": false});
      } catch (e) {
        _num++;

        if (_num >= 3) {
          Toast.fail(title: "视频获取失败,$_num");

          // 执行回调
          if (callback != null)
            callback({"isComplete": true, "isConnectFail": true});

          print("视频错误内容：${e}");
        } else {
          // 递归
          startRealPlay(callback: callback);
        }
      }
    });
  }

  // 销毁视频播放
  static releaseRealPlay() async {
    if (_canclTimer != null) {
      _canclTimer.cancel();
    }
    return await FlutterYs7.videoRelease();
  }

  /// 开启麦克风（开启对讲）
  static Future<bool> startVoiceTalk() async {
    // 请求录音权限
    bool isMicrophoneGranted = await Permission.microphone.isGranted;

    if (!isMicrophoneGranted) await Permission.microphone.request();

    // 打开对讲
    bool startVoiceTalk = await FlutterYs7.startVoiceTalk();

    if (!startVoiceTalk) Toast.fail(title: "麦克风开启失败");

    // 返回结果
    return startVoiceTalk;
  }

  /// 关闭麦克风（关闭对讲）
  static Future<bool> closeVoiceTalk() async {
    // 关闭对讲
    bool stopVoiceTalk = await FlutterYs7.stopVoiceTalk();

    if (!stopVoiceTalk) Toast.fail(title: "麦克风关闭失败");

    return !stopVoiceTalk;
  }

  // 开启音量（听筒）
  static Future<bool> openVolume() async {
    bool openSoundResult = await FlutterYs7.openSound();

    if (!openSoundResult) Toast.fail(title: "音量开启失败");

    return openSoundResult;
  }

  // 关闭音量（听筒）
  static Future<bool> closeVolume() async {
    bool closeSoundResult = await FlutterYs7.closeSound();

    if (!closeSoundResult) Toast.fail(title: "音量关闭失败");

    return !closeSoundResult;
  }

  // 单例
  Video._();
  static Video _currentVideo = Video._();

  /// 获取video的实例对象
  /// * [sdk] sdk|String|选填
  /// * [token] token|String|选填
  /// * [serialNum] serialNum|String|选填
  /// * [code] code|String|选填
  static Video getInstance({
    String sdk,
    String token,
    String serialNum,
    String code,
    int num,
  }) {
    _sdk = sdk;
    _token = token;
    _serialNum = serialNum;
    _code = code;
    _num = num;
    return _currentVideo;
  }
}
